using System.Net;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using DnsService.Events;
using DnsService.Interfaces;
using DnsService.Models;
using LocalDnsSdk.Formatting;
using NLog;

namespace DnsService.Services
{
    /// <summary>
    /// 本地DNS服务实现
    /// 作者：huobing
    /// </summary>
    public class LocalDnsService : IDnsService
    {
        #region 字段和属性

        private UdpClient? _udpClient;
        private CancellationTokenSource? _cancellationTokenSource;
        private Task? _listenerTask;
        private bool _isRunning = false;
        private bool _disposed = false;
        private readonly ConcurrentDictionary<string, DnsCacheItem> _dnsCache = new();
        private readonly ConcurrentDictionary<string, DnsRecord> _dnsRecords = new();
        private readonly List<string> _upstreamDnsServers = [];
        // 索引：按上游DNS服务器IP记录域名集合，用于网络变化时精准清理缓存
        private readonly System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<string, byte>> _upstreamCacheIndex = new();
        private readonly object _upstreamLock = new ();
        private string? _lastUsedUpstreamServer;
        private readonly int _port;
        private readonly DnsCacheStatistics _cacheStatistics = new();
        private readonly DnsRecordStatistics _recordStatistics = new();
        private System.Threading.Timer? _cacheCleanupTimer;
        private DateTime _startTime = DateTime.MinValue;
        
        // 日志记录器
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        
        // 缓存统计相关字段
        private readonly object _cacheLock = new();
        private readonly bool _enableSocketManagement = false;
        private readonly int _socketManagementPort = 8080;
        
        // 上游DNS主域名映射（持久化于 Conf/upstream_domains.conf）
        private readonly ConcurrentDictionary<string, string> _upstreamMainDomains = new(StringComparer.OrdinalIgnoreCase);
        
        // 泛域名配置管理相关字段
        private WildcardDnsConfigManager? _wildcardConfigManager;
        private readonly bool _enableWildcardResolution = false;
        // 访问控制相关字段
        private readonly bool _enableAccessControl = false;
        private readonly List<string> _allowedIps = [];

        /// <summary>
        /// 获取服务是否正在运行
        /// </summary>
        public bool IsRunning => _isRunning;

        /// <summary>
        /// 获取监听端口
        /// </summary>
        public int Port => _port;

        /// <summary>
        /// 获取上游DNS服务器列表
        /// </summary>
        public List<string> UpstreamServers => [.. _upstreamDnsServers];

        /// <summary>
        /// 更新上游DNS优先级（将指定列表置于首位，保留原有其他并去重）
        /// </summary>
        public void UpdatePreferredUpstreamDnsServers(IEnumerable<string>? preferred)
        {
            if (preferred == null) return;
            var pref = preferred.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
            lock (_upstreamLock)
            {
                var rest = _upstreamDnsServers.Where(s => !pref.Contains(s)).ToList();
                _upstreamDnsServers.Clear();
                _upstreamDnsServers.AddRange(pref);
                _upstreamDnsServers.AddRange(rest);
            }
            _logger.Info($"更新上游DNS优先级: {string.Join(", ", _upstreamDnsServers)}");
        }

        /// <summary>
        /// 根据上游DNS服务器IP清除缓存（清除由这些上游DNS产生的域名缓存）
        /// </summary>
        public void ClearCacheByUpstreamDnsServers(IEnumerable<string>? dnsServers)
        {
            if (dnsServers == null) return;
            foreach (var dns in dnsServers)
            {
                if (_upstreamCacheIndex.TryRemove(dns, out var domains))
                {
                    foreach (var kv in domains.Keys)
                    {
                        _dnsCache.TryRemove(kv, out _);
                    }
                    _logger.Info($"已清除来自上游DNS {dns} 的缓存 {domains.Count} 项");
                }
            }
        }

        /// <summary>
        /// 获取DNS缓存记录数量
        /// </summary>
        public int CacheCount => _dnsCache.Count;

        /// <summary>
        /// 获取DNS记录数量
        /// </summary>
        public int DnsRecordsCount => _dnsRecords.Count;

        /// <summary>
        /// 获取服务运行时间
        /// </summary>
        public TimeSpan Uptime
        {
            get
            {
                if (!_isRunning || _startTime == DateTime.MinValue)
                {
                    return TimeSpan.Zero;
                }
                return DateTime.Now - _startTime;
            }
        }

        /// <summary>
        /// 获取DNS缓存记录
        /// </summary>
        public Dictionary<string, DnsCacheItem> DnsCache
        {
            get
            {
                CleanExpiredCache();
                return new(_dnsCache);
            }
        }
        
        /// <summary>
        /// 获取DNS缓存统计信息
        /// </summary>
        public DnsCacheStatistics CacheStatistics
        {
            get
            {
                _cacheStatistics.TotalItems = _dnsCache.Count;
                _cacheStatistics.LastCleanup = DateTime.Now;
                return _cacheStatistics;
            }
        }

        // 获取上游DNS信息（用于展示）
        public System.Collections.Generic.List<DnsService.Models.UpstreamDnsInfo> GetUpstreamDnsInfos()
        {
            var list = new System.Collections.Generic.List<DnsService.Models.UpstreamDnsInfo>();
            lock (_upstreamLock)
            {
                foreach (var ip in _upstreamDnsServers)
                {
                    int count = 0;
                    if (_upstreamCacheIndex.TryGetValue(ip, out var domains))
                    {
                        count = domains.Count;
                    }
                    _upstreamMainDomains.TryGetValue(ip, out var mainDomain);
                    list.Add(new DnsService.Models.UpstreamDnsInfo
                    {
                        Ip = ip,
                        CacheCount = count,
                        MainDomain = string.IsNullOrWhiteSpace(mainDomain) ? string.Empty : mainDomain
                    });
                }
            }
            return list;
        }

        /// <summary>
        /// 获取是否启用Socket管理
        /// </summary>
        public bool EnableSocketManagement => _enableSocketManagement;

        /// <summary>
        /// 获取Socket管理端口
        /// </summary>
        public int SocketManagementPort => _socketManagementPort;

        /// <summary>
        /// 获取Socket管理器实例
        /// </summary>
        public ISocketManager? SocketManager { get; private set; }

        /// <summary>
        /// DNS请求处理事件
        /// </summary>
        public event EventHandler<DnsRequestEventArgs>? DnsRequestProcessed;



        /// <summary>
        /// 服务状态变化事件
        /// </summary>
        public event EventHandler<DnsServiceStatusEventArgs>? StatusChanged;

        /// <summary>
        /// Socket服务器启动事件
        /// </summary>
        public event EventHandler<Events.SocketServerEventArgs>? SocketServerStarted;
        
        /// <summary>
        /// Socket服务器停止事件
        /// </summary>
        public event EventHandler<Events.SocketServerEventArgs>? SocketServerStopped;
        
        /// <summary>
        /// Socket客户端连接事件
        /// </summary>
        public event EventHandler<Events.SocketClientEventArgs>? SocketClientConnected;
        
        /// <summary>
        /// Socket客户端断开事件
        /// </summary>
        public event EventHandler<Events.SocketClientEventArgs>? SocketClientDisconnected;
        
        /// <summary>
        /// Socket消息接收事件
        /// </summary>
        public event EventHandler<Events.SocketMessageEventArgs>? SocketMessageReceived;

        #endregion

        #region 文本命令处理方法

        /// <summary>
        /// 处理ADD/ADDRECORD命令
        /// 格式: ADD domain ip [ttl] [description]（兼容别名：ADDRECORD/ADD_RECORD）
        /// </summary>
        private async Task HandleAddRecordTextCommand(string[] parameters, Models.SocketClientInfo clientInfo)
        {
            if (parameters.Length < 2)
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "缺少必要参数: domain 和 ip");
                return;
            }

            string domain = parameters[0];
            string ip = parameters[1];
            int ttl = 0; // 0表示使用默认TTL
            string description = "";

            // 处理可选的TTL参数
            if (parameters.Length >= 3)
            {
                if (!int.TryParse(parameters[2], out ttl) || ttl < 0)
                {
                    await SendErrorResponseAsync(clientInfo.ClientId, "无效的TTL值");
                    return;
                }
            }

            // 处理可选的描述参数
            if (parameters.Length >= 4)
            {
                description = parameters[3];
            }

            // 验证domain和ip格式
            if (string.IsNullOrWhiteSpace(domain))
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "域名不能为空");
                return;
            }

            if (!IPAddress.TryParse(ip, out _))
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "无效的IP地址格式");
                return;
            }

            // 添加DNS记录
            bool success = AddDnsRecord(domain, ip, "A", ttl, description);
            if (success)
            {
                // 获取实际使用的TTL（考虑默认值）
                int actualTtl = ttl > 0 ? ttl : GetDefaultRecordTtl();
                await SendSuccessResponseAsync(clientInfo.ClientId, $"域名解析记录已添加: {domain} -> {ip}, TTL: {actualTtl}");
                // 成功后同步到配置文件（增量覆盖写入当前内存快照）
                try
                {
                    var cfgMgr = new DnsConfigManager();
                    if (cfgMgr.Config.EnableRecordPersistence)
                    {
                        var filePath = string.IsNullOrWhiteSpace(cfgMgr.Config.RecordFilePath) ? "dns.conf" : cfgMgr.Config.RecordFilePath;
                        ExportDnsRecords(filePath);
                    }
                }
                catch (Exception ex)
            {
                _logger.Error(ex, $"同步记录到文件失败: {ex.Message}");
            }
            }
            else
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "添加域名解析记录失败");
            }
        }

        /// <summary>
        /// 处理REMOVE/REMOVERECORD命令
        /// 格式: REMOVE domain（兼容别名：REMOVERECORD/REMOVE_RECORD）
        /// </summary>
        private async Task HandleRemoveRecordTextCommand(string[] parameters, Models.SocketClientInfo clientInfo)
        {
            if (parameters.Length < 1)
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "缺少必要参数: domain");
                return;
            }

            string domain = parameters[0];
            bool success = RemoveDnsRecord(domain);
            
            if (success)
            {
                await SendSuccessResponseAsync(clientInfo.ClientId, $"域名解析记录已删除: {domain}");
                // 成功后同步到配置文件（增量覆盖写入当前内存快照）
                try
                {
                    var cfgMgr = new DnsConfigManager();
                    if (cfgMgr.Config.EnableRecordPersistence)
                    {
                        var filePath = string.IsNullOrWhiteSpace(cfgMgr.Config.RecordFilePath) ? "dns.conf" : cfgMgr.Config.RecordFilePath;
                        ExportDnsRecords(filePath);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"同步记录到文件失败: {ex.Message}");
                }
            }
            else
            {
                await SendErrorResponseAsync(clientInfo.ClientId, $"删除域名解析记录失败: {domain} 不存在");
            }
        }

        /// <summary>
        /// 处理STATUS命令
        /// 格式: STATUS
        /// </summary>
        private async Task HandleStatusCommand(Models.SocketClientInfo clientInfo)
        {
            string status = _isRunning ? "运行中" : "已停止";
            string startTime = _isRunning ? _startTime.ToString("yyyy-MM-dd HH:mm:ss") : "N/A";
            string socketStatus = _enableSocketManagement ? "已启用" : "已禁用";
            
            await SendTextResponseAsync(clientInfo.ClientId, $"OK: DNS服务状态 - 运行状态: {status}");
            await SendTextResponseAsync(clientInfo.ClientId, $"OK: 启动时间: {startTime}");
            await SendTextResponseAsync(clientInfo.ClientId, $"OK: 监听端口: {_port}");
            await SendTextResponseAsync(clientInfo.ClientId, $"OK: Socket管理: {socketStatus}");
            await SendTextResponseAsync(clientInfo.ClientId, $"OK: 上游DNS: {string.Join(", ", _upstreamDnsServers)}");
        }

        /// <summary>
        /// 处理LIST_RECORDS命令
        /// 格式: LIST_RECORDS
        /// </summary>
        private async Task HandleListRecordsCommand(Models.SocketClientInfo clientInfo)
        {
            var records = _dnsRecords.Values.ToList();
            
            if (records.Count == 0)
            {
                await SendSuccessResponseAsync(clientInfo.ClientId, "当前没有域名解析记录");
                return;
            }

            await SendTextResponseAsync(clientInfo.ClientId, $"OK: 共有 {records.Count} 条域名解析记录");
            foreach (var record in records)
            {
                if (string.Equals(record.RecordType, "PTR", StringComparison.OrdinalIgnoreCase))
                {
                    await SendTextResponseAsync(clientInfo.ClientId,
                        $"OK: PTR记录 ({record.IP}:PTR -> {record.Domain}), TTL: {record.Ttl}, {record.Description}");
                }
                else
                {
                    await SendTextResponseAsync(clientInfo.ClientId,
                        $"OK: {record.Domain} -> {record.IP}, TTL: {record.Ttl}, {record.Description}");
                }
            }
        }

        /// <summary>
        /// 处理CLEAR_CACHE命令
        /// 格式: CLEAR_CACHE
        /// </summary>
        private async Task HandleClearCacheTextCommand(Models.SocketClientInfo clientInfo)
        {
            ClearCache();
            await SendSuccessResponseAsync(clientInfo.ClientId, "DNS缓存已清空");
        }

        /// <summary>
        /// 处理HELP命令
        /// 格式: HELP
        /// </summary>
        private async Task HandleHelpCommand(Models.SocketClientInfo clientInfo)
        {
            await SendTextResponseAsync(clientInfo.ClientId, "OK: 可用命令列表：");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: STATUS - 显示DNS服务状态");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: START - 启动DNS服务");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: STOP - 停止DNS服务");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: RESTART - 重启DNS服务");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: ADD domain ip [ttl] [description] - 添加域名解析记录");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: ADDRECORD domain ip [ttl] [description] - 添加域名解析记录（ADD别名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: ADD_RECORD domain ip [ttl] [description] - 添加域名解析记录（ADD别名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: ADD_PTR ip hostname [ttl] [description] - 添加指定IP的PTR反向记录");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: ADDPTRRECORD ip hostname [ttl] [description] - 添加指定IP的PTR反向记录（ADD_PTR别名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: REMOVE domain - 删除域名解析记录");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: REMOVERECORD domain - 删除域名解析记录（REMOVE别名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: REMOVE_RECORD domain - 删除域名解析记录（REMOVE别名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: LIST_RECORDS - 列出所有域名解析记录");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: REMOVE_PTR ip - 删除指定IP的PTR反向记录");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: REMOVEPTRRECORD ip - 删除指定IP的PTR反向记录（REMOVE_PTR别名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: CLEAR_RECORDS - 清空所有域名解析记录");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: CLEAR_CACHE - 清空DNS缓存");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: LIST_UPSTREAM - 列出上游DNS信息（IP/缓存计数/主域名）");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: LIST_COMMANDS - 以表格形式列出所有命令");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: SET_LOG_POLICY SIZE|DAILY - 设置日志滚动策略");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: GET_LOG_STATUS - 查看当前日志状态");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: HELP - 显示帮助信息");
            await SendTextResponseAsync(clientInfo.ClientId, "OK: EXIT - 退出连接");
        }

        /// <summary>
        /// 处理EXIT命令
        /// 格式: EXIT
        /// </summary>
        private async Task HandleExitCommand(Models.SocketClientInfo clientInfo)
        {
            await SendSuccessResponseAsync(clientInfo.ClientId, "再见");
            // 可以在这里添加关闭连接的逻辑
        }

        // 其他命令处理方法将在后续实现
        private async Task HandleStartCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "服务已启动"); }
        private async Task HandleStopCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "服务已停止"); }
        private async Task HandleRestartCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "服务已重启"); }
        private async Task HandleClearRecordsCommand(Models.SocketClientInfo clientInfo) {
            ClearDnsRecords();
            // 同步到配置文件
            try
            {
                var cfgMgr = new DnsConfigManager();
                if (cfgMgr.Config.EnableRecordPersistence)
                {
                    var filePath = string.IsNullOrWhiteSpace(cfgMgr.Config.RecordFilePath) ? "dns.conf" : cfgMgr.Config.RecordFilePath;
                    ExportDnsRecords(filePath);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"同步记录到文件失败: {ex.Message}");
            }
            await SendSuccessResponseAsync(clientInfo.ClientId, "所有记录已清空");
        }
        private async Task HandleGetCacheStatsCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "缓存统计信息"); }
        private async Task HandleGetConfigCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "配置信息"); }
        private async Task HandleSetConfigCommand(string[] parameters, Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "配置已设置"); }
        private async Task HandleSaveConfigCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "配置已保存"); }
        private async Task HandleGetStatisticsCommand(Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "统计信息"); }
        private async Task HandleResolveCommand(string[] parameters, Models.SocketClientInfo clientInfo) { await SendSuccessResponseAsync(clientInfo.ClientId, "解析结果"); }

        private async Task HandleRemovePtrRecordTextCommand(string[] parameters, Models.SocketClientInfo clientInfo)
        {
            if (parameters.Length < 1)
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "缺少必要参数: ip");
                return;
            }

            string ip = parameters[0];
            if (!IPAddress.TryParse(ip, out _))
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "无效的IP地址格式");
                return;
            }

            bool success = RemovePtrRecord(ip);
            if (success)
            {
                await SendSuccessResponseAsync(clientInfo.ClientId, $"反向解析记录已删除: {ip}");
                // 成功后同步到配置文件（增量覆盖写入当前内存快照）
                try
                {
                    var cfgMgr = new DnsConfigManager();
                    if (cfgMgr.Config.EnableRecordPersistence)
                    {
                        var filePath = string.IsNullOrWhiteSpace(cfgMgr.Config.RecordFilePath) ? "dns.conf" : cfgMgr.Config.RecordFilePath;
                        ExportDnsRecords(filePath);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"同步记录到文件失败: {ex.Message}");
                }
            }
            else
            {
                await SendErrorResponseAsync(clientInfo.ClientId, $"删除反向解析记录失败: {ip} 不存在");
            }
        }

        private async Task HandleAddPtrRecordTextCommand(string[] parameters, Models.SocketClientInfo clientInfo)
        {
            if (parameters.Length < 2)
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "缺少必要参数: ip 和 hostname");
                return;
            }

            string ip = parameters[0];
            string hostname = parameters[1];
            int ttl = 0; // 0表示使用默认TTL
            string description = "";

            if (parameters.Length >= 3)
            {
                if (!int.TryParse(parameters[2], out ttl) || ttl < 0)
                {
                    await SendErrorResponseAsync(clientInfo.ClientId, "无效的TTL值");
                    return;
                }
            }

            if (parameters.Length >= 4)
            {
                description = parameters[3];
            }

            if (!IPAddress.TryParse(ip, out _))
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "无效的IP地址格式");
                return;
            }

            if (string.IsNullOrWhiteSpace(hostname))
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "主机名不能为空");
                return;
            }

            bool addSuccess = AddPtrRecord(ip, hostname, ttl, description);
            if (addSuccess)
            {
                int actualTtl = ttl > 0 ? ttl : GetDefaultRecordTtl();
                await SendSuccessResponseAsync(clientInfo.ClientId, $"反向解析记录已添加: {ip} -> {hostname}, TTL: {actualTtl}");
                // 成功后同步到配置文件（增量覆盖写入当前内存快照）
                try
                {
                    var cfgMgr = new DnsConfigManager();
                    if (cfgMgr.Config.EnableRecordPersistence)
                    {
                        var filePath = string.IsNullOrWhiteSpace(cfgMgr.Config.RecordFilePath) ? "dns.conf" : cfgMgr.Config.RecordFilePath;
                        ExportDnsRecords(filePath);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"同步记录到文件失败: {ex.Message}");
                }
            }
            else
            {
                await SendErrorResponseAsync(clientInfo.ClientId, "添加反向解析记录失败");
            }
        }

        #endregion

        #region 构造函数



        /// <summary>
        /// 构造函数
        /// </summary>
        public LocalDnsService()
        {
            IDnsConfigManager configManager = new DnsConfigManager();
            if (configManager == null)
                throw new ArgumentNullException(nameof(configManager));

            var config = configManager.Config;
            _port = config.Port;
            _enableSocketManagement = config.EnableSocketManagement;
            _socketManagementPort = config.SocketManagementPort;
            _enableWildcardResolution = config.EnableWildcardResolution;
            // 访问控制配置
            _enableAccessControl = config.EnableAccessControl;
            if (_enableAccessControl && config.AllowedIPs != null)
            {
                _allowedIps.AddRange(config.AllowedIPs);
            }
            
            // 添加上游DNS服务器
            if (config.UpstreamDnsServers != null)
            {
                _upstreamDnsServers.AddRange(config.UpstreamDnsServers);
            }
            
            // 如果没有指定上游DNS服务器，添加默认值
            if (_upstreamDnsServers.Count == 0)
            {
                _upstreamDnsServers.Add("8.8.8.8");
                _upstreamDnsServers.Add("114.114.114.114");
            }
            
            // 加载上游主域名映射
            try
            {
                var mgr = new DnsService.Utilities.UpstreamDomainManager();
                var map = mgr.Load();
                foreach (var kv in map)
                {
                    _upstreamMainDomains[kv.Key] = kv.Value;
                }
                _logger.Info($"已加载上游主域名配置 {map.Count} 项");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"加载上游主域名配置失败: {ex.Message}");
            }
            
            // 如果启用Socket管理，创建Socket管理器
            if (_enableSocketManagement)
            {
                InitializeSocketManager();
            }
            
            // 如果启用泛域名解析，创建泛域名配置管理器
            if (_enableWildcardResolution)
            {
                InitializeWildcardConfigManager(config.ForwardRecordFilePath, config.ReverseRecordFilePath, config.DnsRecordConfigWatchInterval);
            }
        }

        /// <summary>
        /// 构造函数（支持Socket管理配置）
        /// </summary>
        /// <param name="port">监听端口</param>
        /// <param name="upstreamDnsServers">上游DNS服务器列表（逗号分隔）</param>
        /// <param name="enableSocketManagement">是否启用Socket管理</param>
        /// <param name="socketManagementPort">Socket管理端口</param>
        public LocalDnsService(int port = 53, string upstreamDnsServers = "8.8.8.8,114.114.114.114", 
            bool enableSocketManagement = false, int socketManagementPort = 8080)
        {
            _port = port;
            _enableSocketManagement = enableSocketManagement;
            _socketManagementPort = socketManagementPort;
            
            // 解析上游DNS服务器
            if (!string.IsNullOrWhiteSpace(upstreamDnsServers))
            {
                var servers = upstreamDnsServers.Split(',', StringSplitOptions.RemoveEmptyEntries);
                foreach (var server in servers)
                {
                    var trimmedServer = server.Trim();
                    if (!string.IsNullOrWhiteSpace(trimmedServer))
                    {
                        _upstreamDnsServers.Add(trimmedServer);
                    }
                }
            }
            
            // 如果没有指定上游DNS服务器，添加默认值
            if (_upstreamDnsServers.Count == 0)
            {
                _upstreamDnsServers.Add("8.8.8.8");
                _upstreamDnsServers.Add("114.114.114.114");
            }
            
            // 如果启用Socket管理，创建Socket管理器
            if (_enableSocketManagement)
            {
                InitializeSocketManager();
            }
        }

        #endregion

        #region Socket管理相关方法

        /// <summary>
        /// 初始化Socket管理器
        /// </summary>
        private void InitializeSocketManager()
        {
            try
            {
                SocketManager = new SocketManager();
                
                // 订阅Socket管理器事件
                SocketManager.ServerStarted += OnSocketServerStarted;
                SocketManager.ServerStopped += OnSocketServerStopped;
                SocketManager.ClientConnected += OnSocketClientConnected;
                SocketManager.ClientDisconnected += OnSocketClientDisconnected;
                SocketManager.MessageReceived += OnSocketMessageReceived;
                
                _logger.Info("Socket管理器初始化成功");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"初始化Socket管理器失败: {ex.Message}");
                SocketManager = null;
            }
        }

        /// <summary>
        /// 初始化泛域名配置管理器
        /// </summary>
        /// <param name="forwardConfigFilePath">正向记录配置文件路径</param>
        /// <param name="reverseConfigFilePath">反向记录配置文件路径</param>
        private void InitializeWildcardConfigManager(string forwardConfigFilePath, string? reverseConfigFilePath, int watchIntervalSeconds)
        {
            try
            {
                _wildcardConfigManager = new WildcardDnsConfigManager(forwardConfigFilePath, reverseConfigFilePath, watchIntervalSeconds);
                
                // 开始监控配置文件变化
                _wildcardConfigManager.StartWatching();
                
                _logger.Info($"DNS记录配置管理器初始化成功，配置文件: {forwardConfigFilePath}{(string.IsNullOrWhiteSpace(reverseConfigFilePath) ? string.Empty : $", {reverseConfigFilePath}")}, 监控间隔(秒): {watchIntervalSeconds}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"初始化DNS记录配置管理器失败: {ex.Message}");
                _wildcardConfigManager = null;
            }
        }

        /// <summary>
        /// 启动Socket管理服务
        /// </summary>
        /// <returns>是否启动成功</returns>
        private async Task<bool> StartSocketManagementAsync()
        {
            if (!_enableSocketManagement || SocketManager == null)
            {
                return false;
            }

            try
            {
                bool success = await SocketManager.StartAsync(_socketManagementPort);
                if (success)
                {
                    _logger.Info($"Socket管理服务已启动，监听端口: {_socketManagementPort}");
                }
                else
                {
                    _logger.Error("Socket管理服务启动失败");
                }
                return success;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"启动Socket管理服务时发生错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 停止Socket管理服务
        /// </summary>
        private void StopSocketManagement()
        {
            if (SocketManager != null)
            {
                SocketManager.Stop();
                _logger.Info("Socket管理服务已停止");
            }
        }

        /// <summary>
        /// 停止Socket管理服务（异步版本）
        /// </summary>
        private async Task StopSocketManagementAsync()
        {
            if (SocketManager != null)
            {
                await SocketManager.StopAsync();
                _logger.Info("Socket管理服务已停止");
            }
        }

        /// <summary>
        /// Socket服务器启动事件处理
        /// </summary>
        private void OnSocketServerStarted(object? sender, Events.SocketServerEventArgs e)
        {
            SocketServerStarted?.Invoke(this, e);
            _logger.Info($"Socket服务器已启动: {e.Message}");
        }

        /// <summary>
        /// Socket服务器停止事件处理
        /// </summary>
        private void OnSocketServerStopped(object? sender, Events.SocketServerEventArgs e)
        {
            SocketServerStopped?.Invoke(this, e);
            _logger.Info($"Socket服务器已停止: {e.Message}");
        }

        /// <summary>
        /// Socket客户端连接事件处理
        /// </summary>
        private void OnSocketClientConnected(object? sender, Events.SocketClientEventArgs e)
        {
            SocketClientConnected?.Invoke(this, e);
            _logger.Info($"Socket客户端连接: {e.ClientInfo?.IPAddress}");
        }

        /// <summary>
        /// Socket客户端断开事件处理
        /// </summary>
        private void OnSocketClientDisconnected(object? sender, Events.SocketClientEventArgs e)
        {
            SocketClientDisconnected?.Invoke(this, e);
            _logger.Info($"Socket客户端断开: {e.ClientInfo?.IPAddress}");
        }

        /// <summary>
        /// Socket消息接收事件处理
        /// </summary>
        private void OnSocketMessageReceived(object? sender, Events.SocketMessageEventArgs e)
        {
            SocketMessageReceived?.Invoke(this, e);
            
            // 异步处理接收到的消息，避免阻塞事件处理线程
            _ = Task.Run(async () => {
                try
                {
                    await HandleSocketMessage(e.Message, e.ClientInfo);
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"异步处理Socket消息时发生错误: {ex.Message}");
                }
            });
        }

        /// <summary>
        /// 处理Socket消息（文本命令格式）
        /// </summary>
        /// <param name="message">消息内容（文本命令）</param>
        /// <param name="clientInfo">客户端信息</param>
        private async Task HandleSocketMessage(string? message, Models.SocketClientInfo? clientInfo)
        {
            if (string.IsNullOrWhiteSpace(message) || clientInfo == null)
            {
                return;
            }

            try
            {
                // 去除前后空白字符
                string commandLine = message.Trim();
                if (string.IsNullOrEmpty(commandLine))
                {
                    return;
                }

                // 使用指令注册器解析并验证
                if (!LocalDnsSdk.Commands.CommandRegistry.TryResolve(commandLine, out var resolved, out var parameters, out var validationError))
                {
                    await SendErrorResponseAsync(clientInfo.ClientId, validationError);
                    return;
                }
                var command = resolved!.Name;

                // 根据命令类型处理（别名已在注册器规范化为主命令）
                switch (command)
                {
                    case LocalDnsSdk.Commands.StatusCommand.NAME:
                        await HandleStatusCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.StartCommand.NAME:
                        await HandleStartCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.StopCommand.NAME:
                        await HandleStopCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.RestartCommand.NAME:
                        await HandleRestartCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.AddCommand.NAME:
                        await HandleAddRecordTextCommand(parameters, clientInfo);
                        break;
                    case LocalDnsSdk.Commands.AddPtrCommand.NAME:
                        await HandleAddPtrRecordTextCommand(parameters, clientInfo);
                        break;
                    case LocalDnsSdk.Commands.RemoveCommand.NAME:
                        await HandleRemoveRecordTextCommand(parameters, clientInfo);
                        break;
                    case LocalDnsSdk.Commands.ListRecordsCommand.NAME:
                        await HandleListRecordsCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.ClearRecordsCommand.NAME:
                        await HandleClearRecordsCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.ClearCacheCommand.NAME:
                        await HandleClearCacheTextCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.GetCacheStatsCommand.NAME:
                        await HandleGetCacheStatsCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.GetConfigCommand.NAME:
                        await HandleGetConfigCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.SetConfigCommand.NAME:
                        await HandleSetConfigCommand(parameters, clientInfo);
                        break;
                    case LocalDnsSdk.Commands.SaveConfigCommand.NAME:
                        await HandleSaveConfigCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.GetStatisticsCommand.NAME:
                        await HandleGetStatisticsCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.ResolveCommand.NAME:
                        await HandleResolveCommand(parameters, clientInfo);
                        break;
                    case LocalDnsSdk.Commands.ExitCommand.NAME:
                        await HandleExitCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.HelpCommand.NAME:
                        await HandleHelpCommand(clientInfo);
                        break;
                    case LocalDnsSdk.Commands.RemovePtrCommand.NAME:
                        await HandleRemovePtrRecordTextCommand(parameters, clientInfo);
                        break;
                    case LocalDnsSdk.Commands.ListUpstreamCommand.NAME:
                    {
                        var infos = GetUpstreamDnsInfos();
                        if (infos.Count == 0)
                        {
                            await SendSuccessResponseAsync(clientInfo.ClientId, "当前没有配置上游DNS");
                        }
                        else
                        {
                            var upstreamRows = new List<string[]>();
                            upstreamRows.Add(new[] { "IP", "CacheCount", "MainDomain" });
                            foreach (var info in infos)
                            {
                                upstreamRows.Add(new[] { info.Ip ?? string.Empty, info.CacheCount.ToString(), info.MainDomain ?? string.Empty });
                            }
                            var upstreamTable = TextTableFormatter.FormatAlignedTable(upstreamRows);
                            await SendTextResponseAsync(clientInfo.ClientId, upstreamTable);
                        }
                        break;
                    }
                    case LocalDnsSdk.Commands.ListCommandsCommand.NAME:
                    {
                        var tableRows = LocalDnsSdk.Commands.CommandRegistry.GetTableRows();
                        var tableText = TextTableFormatter.FormatAlignedTable(tableRows);
                        await SendTextResponseAsync(clientInfo.ClientId, tableText);
                        break;
                    }
                    case LocalDnsSdk.Commands.SetUpstreamMainDomainCommand.NAME:
                    {
                        if (parameters.Length < 2)
                        {
                            await SendErrorResponseAsync(clientInfo.ClientId, "用法: SET_UPSTREAM_MAIN_DOMAIN ip main_domain");
                            break;
                        }
                        var ip = parameters[0];
                        var mainDomain = parameters[1];
                        _upstreamMainDomains[ip] = mainDomain;
                        try
                        {
                            var mgr = new DnsService.Utilities.UpstreamDomainManager();
                            var map = mgr.Load();
                            map[ip] = mainDomain;
                            mgr.Save(map);
                            await SendSuccessResponseAsync(clientInfo.ClientId, $"已设置上游主域名: {ip} -> {mainDomain}");
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(ex, $"保存上游主域名配置失败: {ex.Message}");
                            await SendErrorResponseAsync(clientInfo.ClientId, "保存上游主域名配置失败");
                        }
                        break;
                    }
                    default:
                        await SendTextResponseAsync(clientInfo.ClientId, $"ERROR: 未知命令 '{command}'");
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"处理Socket消息时发生错误: {ex.Message}");
                await SendErrorResponseAsync(clientInfo.ClientId, "处理命令时发生错误");
            }
        }

        // JSON格式的命令处理方法已被文本命令格式替代，这些方法不再使用

        /// <summary>
        /// 发送文本格式响应
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="responseText">响应文本</param>
        private async Task SendTextResponseAsync(string? clientId, string responseText)
        {
            if (SocketManager == null) return;
            if (string.IsNullOrEmpty(clientId)) return;
            
            await SocketManager.SendMessageAsync(clientId, responseText);
        }

        /// <summary>
        /// 发送成功响应
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="message">成功消息</param>
        private async Task SendSuccessResponseAsync(string? clientId, string message)
        {
            await SendTextResponseAsync(clientId, $"OK: {message}");
        }

        /// <summary>
        /// 发送错误响应
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="errorMessage">错误消息</param>
        private async Task SendErrorResponseAsync(string? clientId, string errorMessage)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                // 如果clientId为空，记录错误但不发送响应
                _logger.Error($"无法发送错误消息，clientId为空: {errorMessage}");
                return;
            }
            
            await SendTextResponseAsync(clientId, $"ERROR: {errorMessage}");
        }


        #endregion

        #region 公共方法

        /// <summary>
        /// 启动DNS服务
        /// </summary>
        /// <returns>是否启动成功</returns>
        public async Task<bool> StartAsync()
        {
            _logger.Debug("开始执行StartAsync方法");
            
            if (_isRunning)
            {
                _logger.Info("DNS服务已经在运行中");
                return true;
            }

            try
            {
                _logger.Debug($"准备创建UDP客户端，监听端口: {_port}");
                
                // 检查端口是否被占用
                try
                {
                    using (var checkClient = new UdpClient())
                    {
                        checkClient.Client.Bind(new IPEndPoint(IPAddress.Any, _port));
                        _logger.Debug($"端口 {_port} 可用");
                    }
                }
                catch (SocketException socketEx)
                {
                    _logger.Error(socketEx, $"端口 {_port} 已被占用: {socketEx.Message}");
                    throw new Exception($"端口 {_port} 已被占用: {socketEx.Message}", socketEx);
                }
                
                // 创建UDP客户端
                _logger.Debug($"正在创建UDP客户端，绑定端口: {_port}");
                _udpClient = new UdpClient(_port);
                _logger.Debug($"UDP客户端创建成功，已绑定端口: {_port}");
                
                _cancellationTokenSource = new();
                _logger.Debug("创建取消令牌源");
                
                // 启动监听任务
                _logger.Debug("启动DNS请求监听任务");
                _listenerTask = Task.Run(async () => await ListenForDnsRequestsAsync(_cancellationTokenSource.Token));
                _logger.Debug("监听任务已启动");
                
                // 启动自动缓存清理定时器
                _logger.Debug("启动缓存清理定时器");
                StartCacheCleanupTimer();
                
                // 如果启用Socket管理，启动Socket管理服务
                bool socketStarted = true;
                if (_enableSocketManagement)
                {
                    _logger.Debug($"启用Socket管理，准备启动Socket管理服务，端口: {_socketManagementPort}");
                    socketStarted = await StartSocketManagementAsync();
                    _logger.Debug($"Socket管理服务启动结果: {socketStarted}");
                }
                
                _isRunning = true;
                _startTime = DateTime.Now; // 记录启动时间
                
                OnStatusChanged("DNS服务已启动", true);
                _logger.Info($"DNS服务已成功启动，监听端口: {_port}");
                _logger.Info($"上游DNS服务器配置: {string.Join(", ", _upstreamDnsServers)}");
                
                if (_enableSocketManagement)
                {
                    _logger.Info($"Socket管理服务状态: {(socketStarted ? "已启动" : "启动失败")}");
                }
                
                return true;
            }
            catch (Exception ex)
            {
                string errorDetails = $"启动DNS服务失败: {ex.Message}\n{ex.StackTrace}";
                if (ex.InnerException != null)
                {
                    errorDetails += $"\n内部异常: {ex.InnerException.Message}\n{ex.InnerException.StackTrace}";
                }
                
                _logger.Error(ex, errorDetails);
                OnStatusChanged($"启动DNS服务失败: {ex.Message}", false);
                
                try
                {
                    await StopAsync();
                }
                catch (Exception stopEx)
                {
                    _logger.Error(stopEx, "停止服务时发生异常");
                }
                
                return false;
            }
        }

        /// <summary>
        /// 启动DNS服务（同步版本）
        /// </summary>
        /// <returns>是否启动成功</returns>
        public bool Start()
        {
            return StartAsync().GetAwaiter().GetResult();
        }

        /// <summary>
        /// 停止DNS服务
        /// </summary>
        public async Task StopAsync()
        {
            _logger.Debug("开始执行StopAsync方法");
            
            if (!_isRunning)
            {
                _logger.Debug("服务未运行，无需停止");
                return;
            }

            try
            {
                _logger.Debug("正在停止DNS服务...");
                
                // 如果启用Socket管理，停止Socket管理服务
                if (_enableSocketManagement && SocketManager != null)
                {
                    _logger.Debug("停止Socket管理服务");
                    await StopSocketManagementAsync();
                    _logger.Debug("Socket管理服务已停止");
                }
                
                _logger.Debug("取消监听任务");
                _cancellationTokenSource?.Cancel();
                
                // 停止自动缓存清理定时器
                _logger.Debug("停止自动缓存清理定时器");
                StopCacheCleanupTimer();
                _logger.Debug("自动缓存清理定时器已停止");
                
                // 等待监听任务完成
                if (_listenerTask != null && !_listenerTask.IsCompleted)
                {
                    _logger.Debug("等待监听任务完成");
                    try
                    {
                        await _listenerTask.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
                        _logger.Debug("监听任务已完成");
                    }
                    catch (AggregateException)
                    {
                        _logger.Debug("监听任务取消异常（预期行为）");
                        // 任务取消异常是预期的
                    }
                }
                
                _logger.Debug("关闭并释放UDP客户端");
                _udpClient?.Close();
                _udpClient?.Dispose();
                _logger.Debug("UDP客户端已关闭");
                
                _logger.Debug("释放取消令牌源");
                _cancellationTokenSource?.Dispose();
                
                _logger.Debug("更新服务运行状态为停止");
                _isRunning = false;
                
                _logger.Debug("触发服务停止状态变更事件");
                OnStatusChanged("DNS服务已停止", true);
                _logger.Info("DNS服务已成功停止");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"停止DNS服务时发生错误: {ex.Message}");
                _logger.Error($"异常堆栈: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    _logger.Error($"内部异常: {ex.InnerException.Message}");
                    _logger.Error($"内部异常堆栈: {ex.InnerException.StackTrace}");
                }
                OnStatusChanged($"停止DNS服务时发生错误: {ex.Message}", false);
            }
            finally
            {
                _logger.Debug("清理服务资源");
                _udpClient = null;
                _cancellationTokenSource = null;
                _listenerTask = null;
                _logger.Debug("服务资源清理完成");
            }
        }

        /// <summary>
        /// 停止DNS服务（同步版本）
        /// </summary>
        public void Stop()
        {
            StopAsync().GetAwaiter().GetResult();
        }

        /// <summary>
        /// 清空DNS缓存
        /// </summary>
        public void ClearCache()
        {
            lock (_cacheLock)
            {
                _dnsCache.Clear();
                _logger.Info("DNS缓存已清空");
            }
        }

        /// <summary>
        /// 添加DNS记录（快速模式）
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="ip">IP地址</param>
        /// <returns>是否添加成功</returns>
        public bool AddDnsRecord(string domain, string ip)
        {
            // 使用默认参数调用完整版本
            return AddDnsRecord(domain, ip, "A", 3600, "");
        }
        
        /// <summary>
        /// 获取默认记录TTL
        /// </summary>
        /// <returns>默认TTL值（秒）</returns>
        private static int GetDefaultRecordTtl()
        {
            // 默认TTL值为3600秒（1小时）
            return 3600;
        }

        /// <summary>
        /// 添加DNS记录
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="ip">IP地址</param>
        /// <param name="recordType">记录类型</param>
        /// <param name="ttl">生存时间（秒），如果为0则使用默认TTL</param>
        /// <param name="description">记录描述</param>
        /// <returns>是否添加成功</returns>
        public bool AddDnsRecord(string domain, string ip, string recordType, int ttl, string description)
        {
            if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(ip))
            {
                return false;
            }

            try
            {
                // 如果TTL为0，则使用默认TTL
                int finalTtl = ttl <= 0 ? GetDefaultRecordTtl() : ttl;
                
                var recordKey = $"{domain.ToLower()}:{recordType}";
                var dnsRecord = new DnsRecord
                {
                    Domain = domain,
                    IP = ip,
                    RecordType = recordType,
                    Ttl = finalTtl,
                    Description = description,
                    CreatedTime = DateTime.Now,
                    IsEnabled = true
                };
                
                _dnsRecords[recordKey] = dnsRecord;
                
                // 同时添加到缓存
                var cacheItem = new DnsCacheItem
                {
                    Domain = domain,
                    IP = ip,
                    RecordType = recordType,
                    Ttl = finalTtl,
                    QueryCount = 0,
                    Source = "manual"
                };
                
                _dnsCache[domain.ToLower()] = cacheItem;
                
                // 自动添加对应的反向解析记录（PTR），仅针对A/AAAA记录
                if (recordType.Equals("A", StringComparison.OrdinalIgnoreCase) || recordType.Equals("AAAA", StringComparison.OrdinalIgnoreCase))
                {
                    var ptrRecordKey = $"{ip.ToLower()}:PTR"; // 以IP+类型作为键，避免同域多IP冲突
                    var ptrRecord = new DnsRecord
                    {
                        Domain = domain,
                        IP = ip,
                        RecordType = "PTR",
                        Ttl = finalTtl,
                        Description = string.IsNullOrWhiteSpace(description) ? "auto-PTR" : description,
                        CreatedTime = DateTime.Now,
                        IsEnabled = true
                    };
                    _dnsRecords[ptrRecordKey] = ptrRecord;
                    _logger.Info($"自动添加反向记录: {ip} (PTR) -> {domain}, TTL: {finalTtl}");
                }
                
                _logger.Info($"添加DNS记录: {domain} ({recordType}) -> {ip}, TTL: {finalTtl}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"添加DNS记录失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 移除DNS记录
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="recordType">记录类型</param>
        /// <returns>是否移除成功</returns>
        public bool RemoveDnsRecord(string domain, string recordType = "A")
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                return false;
            }

            try
            {
                var domainKey = domain.ToLower();
                var recordKey = $"{domainKey}:{recordType}";
 
                // 先获取现有记录用于同步删除PTR
                _dnsRecords.TryGetValue(recordKey, out var existingRecord);
                
                bool removedFromCache = _dnsCache.TryRemove(domainKey, out _);
                bool removedFromRecords = _dnsRecords.TryRemove(recordKey, out _);
                
                // 如果删除的是A/AAAA记录，且存在对应记录，则同步删除自动生成的PTR记录
                bool removedPtr = false;
                if (removedFromRecords && existingRecord != null &&
                    (recordType.Equals("A", StringComparison.OrdinalIgnoreCase) || recordType.Equals("AAAA", StringComparison.OrdinalIgnoreCase)))
                {
                    var ptrKey = $"{existingRecord.IP.ToLower()}:PTR";
                    removedPtr = _dnsRecords.TryRemove(ptrKey, out _);
                    if (removedPtr)
                    {
                        _logger.Info($"同步移除反向记录: {existingRecord.IP} (PTR) -> {domain}");
                    }
                }
                
                if (removedFromCache || removedFromRecords)
                {
                    _logger.Info($"移除DNS记录: {domain} ({recordType})");
                }
                
                return removedFromCache || removedFromRecords || removedPtr;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"移除DNS记录失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 按IP移除反向解析记录（PTR）
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <returns>是否移除成功</returns>
        public bool RemovePtrRecord(string ip)
        {
            if (string.IsNullOrWhiteSpace(ip))
            {
                return false;
            }

            try
            {
                var ptrKey = $"{ip.ToLower()}:PTR";
                bool removed = _dnsRecords.TryRemove(ptrKey, out _);
                if (removed)
                {
                    _logger.Info($"移除反向记录: {ip} (PTR)");
                }
                return removed;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"移除反向记录失败: {ex.Message}");
                return false;
            }
        }

        public bool AddPtrRecord(string ip, string hostname, int ttl, string description)
        {
            if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(hostname))
            {
                return false;
            }

            try
            {
                int finalTtl = ttl <= 0 ? GetDefaultRecordTtl() : ttl;
                var ptrKey = $"{ip.ToLower()}:PTR";
                var ptrRecord = new DnsRecord
                {
                    Domain = hostname,
                    IP = ip,
                    RecordType = "PTR",
                    Ttl = finalTtl,
                    Description = description,
                    CreatedTime = DateTime.Now,
                    IsEnabled = true
                };

                _dnsRecords[ptrKey] = ptrRecord;
                _logger.Info($"添加反向记录: {ip} (PTR) -> {hostname}, TTL: {finalTtl}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"添加反向记录失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 清除所有DNS记录
        /// </summary>
        public void ClearDnsRecords()
        {
            try
            {
                _dnsRecords.Clear();
                _logger.Info("已清除所有DNS记录");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"清除DNS记录失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取所有DNS记录
        /// </summary>
        /// <returns>DNS记录列表</returns>
        public List<DnsRecord> GetDnsRecords()
        {
            return [.. _dnsRecords.Values];
        }
        
        /// <summary>
        /// 获取DNS记录统计信息
        /// </summary>
        /// <returns>记录统计信息</returns>
        public DnsRecordStatistics GetDnsRecordStatistics()
        {
            _recordStatistics.TotalRecords = _dnsRecords.Count;
            _recordStatistics.ARecordCount = _dnsRecords.Values.Count(r => r.RecordType == "A");
            _recordStatistics.CnameRecordCount = _dnsRecords.Values.Count(r => r.RecordType == "CNAME");
            _recordStatistics.MxRecordCount = _dnsRecords.Values.Count(r => r.RecordType == "MX");
            _recordStatistics.LastUpdated = DateTime.Now;
            return _recordStatistics;
        }
        
        /// <summary>
        /// 添加DNS缓存项
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="cacheItem">DNS缓存项</param>
        /// <returns>是否添加成功</returns>
        public bool AddDnsCacheItem(string domain, DnsService.Models.DnsCacheItem cacheItem)
        {
            if (string.IsNullOrWhiteSpace(domain) || cacheItem == null)
            {
                return false;
            }

            try
            {
                _dnsCache[domain.ToLower()] = cacheItem;
                
                _logger.Info($"添加DNS缓存项: {domain} ({cacheItem.RecordType}) -> {cacheItem.IP}, 来源: {cacheItem.Source}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"添加DNS缓存项失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 移除DNS缓存项
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>是否移除成功</returns>
        public bool RemoveDnsCacheItem(string domain)
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                return false;
            }

            try
            {
                bool removed = _dnsCache.TryRemove(domain.ToLower(), out _);
                
                if (removed)
                {
                    _logger.Info($"移除DNS缓存项: {domain}");
                }
                
                return removed;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"移除DNS缓存项失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 清除所有DNS缓存
        /// </summary>
        public void ClearDnsCache()
        {
            try
            {
                _dnsCache.Clear();
                _logger.Info("已清除所有DNS缓存");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"清除DNS缓存失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 清理过期缓存
        /// </summary>
        /// <returns>清理的缓存项数量</returns>
        public int CleanExpiredCache()
        {
            int removedCount = 0;
            var now = DateTime.Now;
            
            try
            {
                var expiredKeys = _dnsCache.Where(kv => kv.Value.ExpiresAt < now).Select(kv => kv.Key).ToList();
                
                foreach (var key in expiredKeys)
                {
                    if (_dnsCache.TryRemove(key, out _))
                    {
                        removedCount++;
                    }
                }
                
                if (removedCount > 0)
                {
                    _logger.Info($"清理过期缓存: 移除了 {removedCount} 个过期缓存项");
                }
                
                return removedCount;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"清理过期缓存失败: {ex.Message}");
                return 0;
            }
        }
        
        /// <summary>
        /// 获取缓存命中率
        /// </summary>
        /// <returns>命中率百分比</returns>
        public double GetCacheHitRate()
        {
            if (_cacheStatistics.HitCount + _cacheStatistics.MissCount == 0)
            {
                return 0.0;
            }
            
            return (_cacheStatistics.HitCount / (double)(_cacheStatistics.HitCount + _cacheStatistics.MissCount)) * 100.0;
        }
        
        /// <summary>
        /// 导出DNS记录到文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否导出成功</returns>
        public bool ExportDnsRecords(string filePath)
        {
            try
            {
                // 优先使用配置中的正向/反向文件路径进行双文件导出
                var cfgMgr = new DnsConfigManager();
                var forwardPath = cfgMgr.Config.ForwardRecordFilePath;
                var reversePath = cfgMgr.Config.ReverseRecordFilePath;
                var records = GetDnsRecords();
                
                if (!string.IsNullOrWhiteSpace(forwardPath) && !string.IsNullOrWhiteSpace(reversePath))
                {
                    var forwardLines = new List<string>
                    {
                        "# DNS正向记录导出（文本格式）",
                        "# 格式：IP地址 域名 [记录类型] [TTL]",
                        "# 示例：192.168.1.3 a.test.local A 3600",
                        ""
                    };
                    var reverseLines = new List<string>
                    {
                        "# DNS反向记录导出（文本格式）",
                        "# 格式：IP地址 主机名 [记录类型] [TTL]",
                        "# 示例：192.168.1.3 host.example PTR 3600",
                        ""
                    };
                    foreach (var record in records)
                    {
                        var type = string.IsNullOrWhiteSpace(record.RecordType) ? "A" : record.RecordType;
                        var ttl = record.Ttl > 0 ? record.Ttl : GetDefaultRecordTtl();
                        if (!string.Equals(type, "PTR", StringComparison.OrdinalIgnoreCase))
                        {
                            forwardLines.Add($"{record.IP} {record.Domain} {type} {ttl}");
                        }
                        else
                        {
                            reverseLines.Add($"{record.IP} {record.Domain} {type} {ttl}");
                        }
                    }
                    
                    File.WriteAllLines(forwardPath!, forwardLines);
                    File.WriteAllLines(reversePath!, reverseLines);
                    _logger.Info($"导出DNS记录到文本文件: {forwardPath}（正向）与 {reversePath}（反向），共导出 {records.Count} 条记录");
                    return true;
                }
                
                // 回退：单文件导出到传入路径
                var lines = new List<string>
                {
                    "# DNS记录导出（文本格式）",
                    "# 格式：IP地址 域名 [记录类型] [TTL]",
                    "# 示例：192.168.1.3 a.test.local A 3600",
                    ""
                };
                foreach (var record in records)
                {
                    var type = string.IsNullOrWhiteSpace(record.RecordType) ? "A" : record.RecordType;
                    var ttl = record.Ttl > 0 ? record.Ttl : GetDefaultRecordTtl();
                    lines.Add($"{record.IP} {record.Domain} {type} {ttl}");
                }
                File.WriteAllLines(filePath, lines);
                _logger.Info($"导出DNS记录到文本文件: {filePath}, 共导出 {records.Count} 条记录");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"导出DNS记录失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 从文件导入DNS记录
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是否导入成功</returns>
        public bool ImportDnsRecords(string filePath)
        {
            try
            {
                // 优先使用配置中的正向/反向文件路径进行双文件导入
                var cfgMgr = new DnsConfigManager();
                var forwardPath = cfgMgr.Config.ForwardRecordFilePath;
                var reversePath = cfgMgr.Config.ReverseRecordFilePath;
                
                if (!string.IsNullOrWhiteSpace(forwardPath) && !string.IsNullOrWhiteSpace(reversePath))
                {
                    int totalImported = 0;
                    
                    // 正向记录文件导入（默认类型A）
                    if (File.Exists(forwardPath))
                    {
                        var linesFwd = File.ReadAllLines(forwardPath);
                        int importedFwd = 0;
                        foreach (var raw in linesFwd)
                        {
                            var line = raw.Trim();
                            if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue;
                            var parts = line.Split(new[]{'\t',' '}, StringSplitOptions.RemoveEmptyEntries);
                            if (parts.Length < 2) continue;
                            var ip = parts[0];
                            var domain = parts[1];
                            var type = parts.Length >= 3 ? parts[2].ToUpperInvariant() : "A";
                            var ttl = parts.Length >= 4 && int.TryParse(parts[3], out var t) ? t : GetDefaultRecordTtl();
                            
                            if (AddDnsRecord(domain, ip, type, ttl, ""))
                            {
                                importedFwd++;
                            }
                        }
                        _logger.Info($"从正向记录文件导入: {forwardPath}, 成功导入 {importedFwd} 条记录");
                        totalImported += importedFwd;
                    }
                    else
                    {
                        _logger.Error($"导入DNS记录失败: 正向记录文件不存在: {forwardPath}");
                    }
                    
                    // 反向记录文件导入（默认类型PTR）
                    if (File.Exists(reversePath))
                    {
                        var linesRev = File.ReadAllLines(reversePath);
                        int importedRev = 0;
                        foreach (var raw in linesRev)
                        {
                            var line = raw.Trim();
                            if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue;
                            var parts = line.Split(new[]{'\t',' '}, StringSplitOptions.RemoveEmptyEntries);
                            if (parts.Length < 2) continue;
                            var ip = parts[0];
                            var hostname = parts[1];
                            var type = parts.Length >= 3 ? parts[2].ToUpperInvariant() : "PTR";
                            var ttl = parts.Length >= 4 && int.TryParse(parts[3], out var t2) ? t2 : GetDefaultRecordTtl();
                            
                            if (AddDnsRecord(hostname, ip, type, ttl, ""))
                            {
                                importedRev++;
                            }
                        }
                        _logger.Info($"从反向记录文件导入: {reversePath}, 成功导入 {importedRev} 条记录");
                        totalImported += importedRev;
                    }
                    else
                    {
                        _logger.Error($"导入DNS记录失败: 反向记录文件不存在: {reversePath}");
                    }
                    
                    _logger.Info($"双文件导入完成，共导入 {totalImported} 条记录");
                    return totalImported >= 0;
                }
                
                // 回退：单文件导入
                if (!File.Exists(filePath))
                {
                    _logger.Error("导入DNS记录失败: 文件不存在");
                    return false;
                }
                
                var lines = File.ReadAllLines(filePath);
                int importedCount = 0;
                foreach (var raw in lines)
                {
                    var line = raw.Trim();
                    if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue;
                    var parts = line.Split(new[]{'\t',' '}, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length < 2) continue;
                    var ip = parts[0];
                    var domain = parts[1];
                    var type = parts.Length >= 3 ? parts[2].ToUpperInvariant() : "A";
                    var ttl = parts.Length >= 4 && int.TryParse(parts[3], out var t) ? t : GetDefaultRecordTtl();
                    
                    if (AddDnsRecord(domain, ip, type, ttl, ""))
                    {
                        importedCount++;
                    }
                }
                
                _logger.Info($"从文本文件导入DNS记录: {filePath}, 成功导入 {importedCount} 条记录");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"导入DNS记录失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 测试DNS服务器连接
        /// </summary>
        /// <param name="dnsServer">DNS服务器地址</param>
        /// <param name="timeout">超时时间（毫秒）</param>
        /// <returns>测试结果</returns>
        public async Task<DnsTestResult> TestDnsServerAsync(string dnsServer, int timeout = 5000)
        {
            var result = new DnsTestResult(false);
            
            try
            {
                var stopwatch = Stopwatch.StartNew();
                
                using var ping = new Ping();
                var reply = await ping.SendPingAsync(dnsServer, timeout);
                
                stopwatch.Stop();
                
                result.ResponseTimeMs = stopwatch.ElapsedMilliseconds;
                result.IsSuccess = reply.Status == IPStatus.Success;
                
                if (!result.IsSuccess)
                {
                    result.ErrorMessage = $"Ping失败: {reply.Status}";
                }
                
                _logger.Info($"测试DNS服务器 {dnsServer}: {(result.IsSuccess ? "成功" : "失败")}，响应时间: {result.ResponseTimeMs}ms");
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                _logger.Error(ex, $"测试DNS服务器 {dnsServer} 失败: {ex.Message}");
            }
            
            return result;
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 启动自动缓存清理定时器
        /// </summary>
        private void StartCacheCleanupTimer()
        {
            try
            {
                // 每5分钟清理一次过期缓存
                _cacheCleanupTimer = new System.Threading.Timer(CacheCleanupCallback, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));
                _logger.Info("自动缓存清理定时器已启动（每5分钟清理一次过期缓存）");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"启动自动缓存清理定时器失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止自动缓存清理定时器
        /// </summary>
        private void StopCacheCleanupTimer()
        {
            try
            {
                _cacheCleanupTimer?.Dispose();
                _cacheCleanupTimer = null;
                _logger.Info("自动缓存清理定时器已停止");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"停止自动缓存清理定时器失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 缓存清理回调函数
        /// </summary>
        /// <param name="state">状态对象</param>
        private void CacheCleanupCallback(object? state)
        {
            try
            {
                int removedCount = CleanExpiredCache();
                if (removedCount > 0)
                {
                    _logger.Info($"自动清理过期缓存: 移除了 {removedCount} 个过期缓存项");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"自动缓存清理失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 监听DNS请求
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        private async Task ListenForDnsRequestsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested && _udpClient != null)
            {
                try
                {
                    // 接收UDP数据包
                    var receiveResult = await _udpClient.ReceiveAsync(cancellationToken);

                    // 处理DNS请求
                    _ = Task.Run(async () => await ProcessDnsRequestAsync(receiveResult.Buffer, receiveResult.RemoteEndPoint), cancellationToken);
                }
                catch (OperationCanceledException)
                {
                    // 正常取消
                    break;
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"处理DNS请求时发生错误: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 处理DNS请求
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="remoteEndPoint">远程端点</param>
        private async Task ProcessDnsRequestAsync(byte[] requestData, IPEndPoint remoteEndPoint)
        {
            try
            {
                // 解析DNS请求（简化实现）
                var domain = ExtractDomainFromDnsRequest(requestData);
                
                if (string.IsNullOrWhiteSpace(domain))
                {
                    _logger.Info($"收到无效DNS请求，来源: {remoteEndPoint}");
                    return;
                }
                
                // 访问控制：拦截未授权IP
                if (_enableAccessControl)
                {
                    var srcIp = remoteEndPoint.Address;
                    bool allowed = false;

                    // 本地函数：CIDR匹配（支持IPv4/IPv6）
                    static bool IsInCidrLocal(IPAddress ip, string cidr)
                    {
                        try
                        {
                            var parts = cidr.Split('/');
                            if (parts.Length != 2) return false;
                            if (!IPAddress.TryParse(parts[0], out var network)) return false;
                            if (!int.TryParse(parts[1], out var prefixLength)) return false;

                            var ipBytes = ip.GetAddressBytes();
                            var netBytes = network.GetAddressBytes();
                            if (ipBytes.Length != netBytes.Length) return false; // IPv4/IPv6不匹配

                            int fullBytes = prefixLength / 8;
                            int remainderBits = prefixLength % 8;

                            for (int i = 0; i < fullBytes; i++)
                            {
                                if (ipBytes[i] != netBytes[i]) return false;
                            }
                            if (remainderBits > 0)
                            {
                                int mask = 0xFF << (8 - remainderBits);
                                if ((ipBytes[fullBytes] & mask) != (netBytes[fullBytes] & mask)) return false;
                            }
                            return true;
                        }
                        catch
                        {
                            return false;
                        }
                    }

                    // 本地函数：范围匹配（start-end，支持IPv4/IPv6）
                    static bool IsInRangeLocal(IPAddress ip, string range)
                    {
                        try
                        {
                            var parts = range.Split('-', 2);
                            if (parts.Length != 2) return false;
                            if (!IPAddress.TryParse(parts[0].Trim(), out var start)) return false;
                            if (!IPAddress.TryParse(parts[1].Trim(), out var end)) return false;
                            var ipBytes = ip.GetAddressBytes();
                            var startBytes = start.GetAddressBytes();
                            var endBytes = end.GetAddressBytes();
                            if (ipBytes.Length != startBytes.Length || ipBytes.Length != endBytes.Length) return false; // IPv4/IPv6不匹配

                            // 规范化范围顺序
                            int cmpStartEnd = CompareBytes(startBytes, endBytes);
                            if (cmpStartEnd > 0)
                            {
                                var tmp = startBytes; startBytes = endBytes; endBytes = tmp;
                            }

                            // 检查 ip 是否在 [start, end] 范围内
                            return CompareBytes(ipBytes, startBytes) >= 0 && CompareBytes(ipBytes, endBytes) <= 0;

                            // 本地比较函数
                            static int CompareBytes(byte[] a, byte[] b)
                            {
                                for (int i = 0; i < a.Length && i < b.Length; i++)
                                {
                                    int diff = a[i].CompareTo(b[i]);
                                    if (diff != 0) return diff;
                                }
                                return a.Length.CompareTo(b.Length);
                            }
                        }
                        catch
                        {
                            return false;
                        }
                    }

                    if (_allowedIps != null && _allowedIps.Count > 0)
                    {
                        foreach (var rule in _allowedIps)
                        {
                            if (string.IsNullOrWhiteSpace(rule)) continue;
                            if (rule.Contains("/"))
                            {
                                if (IsInCidrLocal(srcIp, rule)) { allowed = true; break; }
                            }
                            else if (rule.Contains("-"))
                            {
                                if (IsInRangeLocal(srcIp, rule)) { allowed = true; break; }
                            }
                            else
                            {
                                if (string.Equals(srcIp.ToString(), rule, StringComparison.OrdinalIgnoreCase)) { allowed = true; break; }
                            }
                        }
                    }

                    if (!allowed)
                    {
                        _logger.Info($"拒绝来自未授权IP的查询: {srcIp}");
                        return;
                    }
                }
                
                _logger.Info($"收到DNS查询: {domain}，来源: {remoteEndPoint}");
                
                // 更新查询统计
                _cacheStatistics.MissCount++;
                
                // 检查是否为反向解析请求（PTR记录）
                string? resolvedIp = null;
                if (domain.EndsWith(".in-addr.arpa") || domain.EndsWith(".ip6.arpa"))
                {
                    // 处理反向解析请求
                    var hostname = await HandleReverseLookupAsync(domain);
                    if (!string.IsNullOrWhiteSpace(hostname))
                    {
                        _logger.Info($"反向解析: {domain} -> {hostname}");
                        // 对于反向解析，我们需要创建特殊的响应
                        var responseData = CreateReverseDnsResponse(requestData, hostname);
                        await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);
                        OnDnsRequestProcessed(domain, hostname, remoteEndPoint.Address.ToString());
                        return; // 已经处理了响应，直接返回
                    }
                }
                else
                {
                    // 正向解析请求
                    // 检查缓存
                    if (_dnsCache.TryGetValue(domain.ToLower(), out var cachedItem))
                    {
                        // 检查缓存是否过期
                        if (cachedItem.ExpiresAt > DateTime.Now)
                        {
                            resolvedIp = cachedItem.IP;
                            cachedItem.LastAccessed = DateTime.Now;
                            cachedItem.QueryCount++;
                            _cacheStatistics.HitCount++;
                            _logger.Info($"从缓存解析: {domain} -> {resolvedIp}");
                        }
                        else
                        {
                            // 缓存过期，移除并重新查询
                            _dnsCache.TryRemove(domain.ToLower(), out _);
                            _logger.Info($"缓存过期: {domain}");
                        }
                    }
                    
                    // 如果缓存未命中或过期，尝试泛域名解析
                    if (string.IsNullOrWhiteSpace(resolvedIp) && _enableWildcardResolution && _wildcardConfigManager != null)
                    {
                        resolvedIp = _wildcardConfigManager.ResolveDomain(domain);
                        if (!string.IsNullOrWhiteSpace(resolvedIp))
                        {
                            // 缓存泛域名解析结果
                            var cacheItem = new DnsService.Models.DnsCacheItem
                            {
                                Domain = domain,
                                IP = resolvedIp,
                                RecordType = "A",
                                Ttl = 3600,
                                Source = "wildcard",
                                CreatedTime = DateTime.Now,
                                LastAccessed = DateTime.Now
                            };
                            AddDnsCacheItem(domain, cacheItem);
                            _logger.Info($"泛域名解析: {domain} -> {resolvedIp}");
                        }
                    }
                    
                    // 如果泛域名解析未命中，向上游DNS服务器查询
                    if (string.IsNullOrWhiteSpace(resolvedIp))
                    {
                        resolvedIp = await QueryUpstreamDnsAsync(domain);
                        
                        if (!string.IsNullOrWhiteSpace(resolvedIp))
                        {
                            // 缓存结果
                            var cacheItem = new DnsService.Models.DnsCacheItem
                            {
                                Domain = domain,
                                IP = resolvedIp,
                                RecordType = "A",
                                Ttl = 3600,
                                Source = "upstream",
                                CreatedTime = DateTime.Now,
                                LastAccessed = DateTime.Now
                            };
                            AddDnsCacheItem(domain, cacheItem);
                            var domLower = domain.ToLower();
                            if (!string.IsNullOrWhiteSpace(_lastUsedUpstreamServer))
                            {
                                var index = _upstreamCacheIndex.GetOrAdd(_lastUsedUpstreamServer, _ => new System.Collections.Concurrent.ConcurrentDictionary<string, byte>());
                                index[domLower] = 0;
                            }
                            _logger.Info($"向上游DNS查询: {domain} -> {resolvedIp}");
                        }
                    }
                }
                
                // 发送响应（简化实现）
                if (!string.IsNullOrWhiteSpace(resolvedIp))
                {
                    var responseData = CreateDnsResponse(requestData, resolvedIp);
                    await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);
                    
                    OnDnsRequestProcessed(domain, resolvedIp, remoteEndPoint.Address.ToString());
                    _logger.Info($"发送DNS响应: {domain} -> {resolvedIp}");
                }
                else
                {
                    _logger.Info($"无法解析域名: {domain}");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"处理DNS请求时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理反向解析请求
        /// </summary>
        /// <param name="reverseDomain">反向域名（如1.0.0.127.in-addr.arpa）</param>
        /// <returns>主机名</returns>
        private async Task<string?> HandleReverseLookupAsync(string reverseDomain)
        {
            try
            {
                // 支持IPv6反向域名（ip6.arpa）：::1 -> localhost
                if (reverseDomain.EndsWith(".ip6.arpa", StringComparison.OrdinalIgnoreCase))
                {
                    var labelPart = reverseDomain.Substring(0, reverseDomain.Length - ".ip6.arpa".Length);
                    var labels = labelPart.Split('.');
                    if (labels.Length == 32 && labels[0] == "1" && labels.Skip(1).All(l => l == "0"))
                    {
                        return "localhost";
                    }
                    // 非 ::1 的 IPv6 反向解析：尝试解析并匹配本地自动生成的PTR记录
                }
                
                // 解析IPv4反向域名：1.0.0.127.in-addr.arpa -> 127.0.0.1
                var parts = reverseDomain.Split('.');
                if (parts.Length < 6) return null;
                
                // 提取IP地址部分（反向顺序）
                var ipParts = new List<string>();
                for (int i = 0; i < 4; i++)
                {
                    if (parts.Length > i) ipParts.Add(parts[i]);
                }
                
                ipParts.Reverse(); // 反转回正常IP顺序
                var ipAddress = string.Join(".", ipParts);
                
                // 默认反向解析：127.0.0.1 -> localhost
                if (ipAddress == "127.0.0.1")
                {
                    return "localhost";
                }
                
                // 查询本地自动生成的PTR记录
                var localPtr = _dnsRecords.Values.FirstOrDefault(r => r.RecordType.Equals("PTR", StringComparison.OrdinalIgnoreCase) && r.IP.Equals(ipAddress, StringComparison.OrdinalIgnoreCase) && r.IsEnabled);
                if (localPtr != null)
                {
                    return localPtr.Domain;
                }
                
                // 使用泛域名配置管理器进行反向解析
                if (_enableWildcardResolution && _wildcardConfigManager != null)
                {
                    var hostname = _wildcardConfigManager.ReverseResolve(ipAddress);
                    if (!string.IsNullOrWhiteSpace(hostname))
                    {
                        return hostname;
                    }
                }
                
                // 向上游DNS服务器查询反向解析
                return await QueryUpstreamDnsForReverseLookupAsync(reverseDomain);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"处理反向解析失败: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 向上游DNS服务器查询反向解析
        /// </summary>
        /// <param name="reverseDomain">反向域名</param>
        /// <returns>主机名</returns>
        private async Task<string?> QueryUpstreamDnsForReverseLookupAsync(string reverseDomain)
        {
            foreach (var dnsServer in _upstreamDnsServers)
            {
                try
                {
                    // 使用指定的DNS服务器进行查询
                    using var dnsClient = new System.Net.Sockets.UdpClient();
                    
                    // 创建DNS查询数据包（PTR记录查询）
                    var queryData = CreatePTRRecordQuery(reverseDomain);
                    
                    // 发送查询到指定的DNS服务器
                    var dnsEndPoint = new IPEndPoint(IPAddress.Parse(dnsServer), 53);
                    await dnsClient.SendAsync(queryData, queryData.Length, dnsEndPoint);
                    
                    // 接收响应（设置超时）
                    var receiveTask = dnsClient.ReceiveAsync();
                    var timeoutTask = Task.Delay(TimeSpan.FromSeconds(5));
                    
                    var completedTask = await Task.WhenAny(receiveTask, timeoutTask);
                    
                    if (completedTask == receiveTask)
                    {
                        var response = receiveTask.Result;
                        var hostname = ExtractHostnameFromDnsResponse(response.Buffer);
                        
                        if (!string.IsNullOrWhiteSpace(hostname))
                        {
                            return hostname;
                        }
                    }
                    else
                    {
                        _logger.Error($"向上游DNS服务器 {dnsServer} 查询反向解析 {reverseDomain} 超时");
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"向上游DNS服务器 {dnsServer} 查询反向解析 {reverseDomain} 失败: {ex.Message}");
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 创建PTR记录查询数据包
        /// </summary>
        /// <param name="reverseDomain">反向域名</param>
        /// <returns>DNS查询数据</returns>
        private static byte[] CreatePTRRecordQuery(string reverseDomain)
        {
            var query = new List<byte>();
            
            // 事务ID (随机)
            var random = new Random();
            query.Add((byte)random.Next(0, 256));
            query.Add((byte)random.Next(0, 256));
            
            // 标志：标准查询，递归查询
            query.Add(0x01); // QR=0, OPCODE=0, AA=0, TC=0, RD=1
            query.Add(0x00); // RA=0, Z=0, RCODE=0
            
            // 问题数量 = 1
            query.Add(0x00);
            query.Add(0x01);
            
            // 回答数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 权威记录数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 附加记录数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 域名部分
            var domainParts = reverseDomain.Split('.');
            foreach (var part in domainParts)
            {
                query.Add((byte)part.Length);
                query.AddRange(Encoding.UTF8.GetBytes(part));
            }
            query.Add(0x00); // 域名结束
            
            // 查询类型 PTR记录 = 12
            query.Add(0x00);
            query.Add(0x0C);
            
            // 查询类 IN = 1
            query.Add(0x00);
            query.Add(0x01);
            
            return [.. query];
        }
        
        /// <summary>
        /// 从DNS响应中提取主机名（PTR记录）
        /// </summary>
        /// <param name="responseData">响应数据</param>
        /// <returns>主机名</returns>
        private string? ExtractHostnameFromDnsResponse(byte[] responseData)
        {
            try
            {
                if (responseData.Length < 12) return null;
                
                // 检查响应码
                var rcode = responseData[3] & 0x0F;
                if (rcode != 0) return null; // 非零表示错误
                
                // 获取回答数量
                var answerCount = (responseData[6] << 8) | responseData[7];
                if (answerCount == 0) return null;
                
                // 跳过问题部分
                int position = 12;
                while (position < responseData.Length && responseData[position] != 0)
                {
                    int length = responseData[position];
                    position += length + 1;
                }
                position += 5; // 跳过结束的0和QType、QClass
                
                // 查找PTR记录
                for (int i = 0; i < answerCount && position < responseData.Length - 10; i++)
                {
                    // 跳过域名指针（2字节）
                    if (responseData[position] == 0xC0)
                    {
                        position += 2;
                    }
                    else
                    {
                        // 跳过域名
                        while (position < responseData.Length && responseData[position] != 0)
                        {
                            int length = responseData[position];
                            position += length + 1;
                        }
                        position++; // 跳过结束的0
                    }
                    
                    // 检查记录类型
                    var type = (responseData[position] << 8) | responseData[position + 1];
                    position += 2;
                    
                    // 跳过类
                    position += 2;
                    
                    // 跳过TTL
                    position += 4;
                    
                    // 获取数据长度
                    var dataLength = (responseData[position] << 8) | responseData[position + 1];
                    position += 2;
                    
                    if (type == 12) // PTR记录
                    {
                        // 提取主机名
                        var hostnameBuilder = new StringBuilder();
                        int endPosition = position + dataLength;
                        
                        while (position < endPosition && position < responseData.Length)
                        {
                            if (responseData[position] == 0xC0) // 指针
                            {
                                int pointerPosition = responseData[position + 1];
                                var pointerHostname = ExtractDomainFromPointer(responseData, pointerPosition);
                                hostnameBuilder.Append(pointerHostname);
                                position += 2;
                                break;
                            }
                            else if (responseData[position] > 0) // 标签
                            {
                                int labelLength = responseData[position];
                                position++;
                                
                                if (position + labelLength <= responseData.Length)
                                {
                                    var label = Encoding.UTF8.GetString(responseData, position, labelLength);
                                    hostnameBuilder.Append(label);
                                    position += labelLength;
                                    
                                    if (position < endPosition && position < responseData.Length && responseData[position] != 0)
                                    {
                                        hostnameBuilder.Append(".");
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else // 结束符
                            {
                                position++;
                                break;
                            }
                        }
                        
                        var hostname = hostnameBuilder.ToString();
                        if (!string.IsNullOrEmpty(hostname))
                        {
                            return hostname;
                        }
                    }
                    
                    position += dataLength;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"从DNS响应提取主机名失败: {ex.Message}");
            }
            
            return null;
        }
        
        /// <summary>
        /// 从DNS响应中的指针提取域名
        /// </summary>
        /// <param name="responseData">响应数据</param>
        /// <param name="pointerPosition">指针位置</param>
        /// <returns>域名</returns>
        private string ExtractDomainFromPointer(byte[] responseData, int pointerPosition)
        {
            var domainBuilder = new StringBuilder();
            int position = pointerPosition;
            
            while (position < responseData.Length)
            {
                if (responseData[position] == 0xC0) // 嵌套指针
                {
                    position += 2;
                }
                else if (responseData[position] > 0) // 标签
                {
                    int labelLength = responseData[position];
                    position++;
                    
                    if (position + labelLength <= responseData.Length)
                    {
                        var label = Encoding.UTF8.GetString(responseData, position, labelLength);
                        domainBuilder.Append(label);
                        position += labelLength;
                        
                        if (position < responseData.Length && responseData[position] != 0)
                        {
                            domainBuilder.Append(".");
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else // 结束符
                {
                    break;
                }
            }
            
            return domainBuilder.ToString();
        }
        
        /// <summary>
        /// 创建反向DNS响应（PTR记录）
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="hostname">主机名</param>
        /// <returns>响应数据</returns>
        private byte[] CreateReverseDnsResponse(byte[] requestData, string hostname)
        {
            try
            {
                // 创建响应列表
                var response = new List<byte>();
                
                // 复制请求头部（事务ID）
                response.AddRange(requestData[0..2]);
                
                // 设置响应标志（设置AA=1表示权威应答）
                response.Add(0x85); // QR=1, OPCODE=0, AA=1, TC=0, RD=1
                response.Add(0x80); // RA=1, Z=0, RCODE=0
                
                // 问题数量（从请求中复制）
                response.AddRange(requestData[4..6]);
                
                // 回答数量 = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // 权威记录数量 = 0
                response.Add(0x00);
                response.Add(0x00);
                
                // 附加记录数量 = 0
                response.Add(0x00);
                response.Add(0x00);
                
                // 复制问题部分（域名查询部分）
                int questionStart = 12;
                int questionEnd = questionStart;
                
                // 找到问题部分的结束位置
                while (questionEnd < requestData.Length && requestData[questionEnd] != 0)
                {
                    int length = requestData[questionEnd];
                    questionEnd += length + 1;
                }
                questionEnd += 5; // 包括结束的0和QType、QClass
                
                if (questionEnd <= requestData.Length)
                {
                    response.AddRange(requestData[questionStart..questionEnd]);
                }
                
                // 添加回答记录
                // 指针到问题部分的域名（0xC0 0x0C）
                response.Add(0xC0);
                response.Add(0x0C);
                
                // 类型 PTR记录 = 12
                response.Add(0x00);
                response.Add(0x0C);
                
                // 类 IN = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // TTL = 300秒
                response.Add(0x00);
                response.Add(0x00);
                response.Add(0x01);
                response.Add(0x2C);
                
                // 构建主机名数据
                var hostnameParts = hostname.Split('.');
                var hostnameData = new List<byte>();
                
                foreach (var part in hostnameParts)
                {
                    hostnameData.Add((byte)part.Length);
                    hostnameData.AddRange(Encoding.UTF8.GetBytes(part));
                }
                hostnameData.Add(0x00); // 结束
                
                // 数据长度
                response.Add((byte)(hostnameData.Count >> 8));
                response.Add((byte)hostnameData.Count);
                
                // 主机名数据
                response.AddRange(hostnameData);
                
                return [.. response];
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"创建反向DNS响应失败: {ex.Message}");
                
                // 返回一个基本的错误响应
                var basicResponse = new List<byte>();
                basicResponse.AddRange(requestData[0..2]); // 事务ID
                basicResponse.Add(0x81); // QR=1
                basicResponse.Add(0x83); // RCODE=3（域名不存在）
                basicResponse.AddRange(new byte[10]); // 其他字段设为0
                return [.. basicResponse];
            }
        }

        /// <summary>
        /// 从DNS请求中提取域名
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <returns>域名</returns>
        private static string ExtractDomainFromDnsRequest(byte[] requestData)
        {
            try
            {
                // 简化实现：假设请求格式为标准的DNS查询
                if (requestData.Length < 12) return string.Empty;
                
                var domainParts = new List<string>();
                int position = 12; // 跳过DNS头部
                
                while (position < requestData.Length && requestData[position] != 0)
                {
                    int length = requestData[position];
                    position++;
                    
                    if (position + length > requestData.Length) break;
                    
                    var part = Encoding.UTF8.GetString(requestData, position, length);
                    domainParts.Add(part);
                    position += length;
                }
                
                return string.Join(".", domainParts);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 向上游DNS服务器查询
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>解析的IP地址</returns>
        private async Task<string?> QueryUpstreamDnsAsync(string domain)
        {
            foreach (var dnsServer in _upstreamDnsServers)
            {
                try
                {
                    // 构建候选查询域名列表：原始域名、主域名、父域名+主域名
                    var candidates = new List<string>();
                    candidates.Add(domain);
                    if (_upstreamMainDomains.TryGetValue(dnsServer, out var baseDomain) && !string.IsNullOrWhiteSpace(baseDomain))
                    {
                        candidates.Add(baseDomain);
                        // 对原始域名的父域名逐级组合为 suffix.baseDomain
                        var parts = domain.Split('.', StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 1; i < parts.Length; i++)
                        {
                            var suffix = string.Join('.', parts.Skip(i));
                            var combined = string.IsNullOrWhiteSpace(suffix) ? baseDomain : $"{suffix}.{baseDomain}";
                            if (!candidates.Contains(combined, StringComparer.OrdinalIgnoreCase))
                                candidates.Add(combined);
                        }
                    }
                    
                    using var dnsClient = new System.Net.Sockets.UdpClient();
                    var dnsEndPoint = new IPEndPoint(IPAddress.Parse(dnsServer), 53);
                    
                    foreach (var cand in candidates)
                    {
                        var queryData = CreateDnsQuery(cand);
                        await dnsClient.SendAsync(queryData, queryData.Length, dnsEndPoint);
                        var receiveTask = dnsClient.ReceiveAsync();
                        var timeoutTask = Task.Delay(TimeSpan.FromSeconds(5));
                        var completedTask = await Task.WhenAny(receiveTask, timeoutTask);
                        if (completedTask == receiveTask)
                        {
                            var response = receiveTask.Result;
                            var ipAddress = ExtractIpFromDnsResponse(response.Buffer);
                            if (!string.IsNullOrWhiteSpace(ipAddress))
                            {
                                _lastUsedUpstreamServer = dnsServer;
                                return ipAddress;
                            }
                        }
                        else
                        {
                            _logger.Error($"向上游DNS服务器 {dnsServer} 查询 {cand} 超时");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"向上游DNS服务器 {dnsServer} 查询 {domain} 失败: {ex.Message}");
                }
            }
            
            return null;
        }

        /// <summary>
        /// 创建DNS查询数据包
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>DNS查询数据</returns>
        private static byte[] CreateDnsQuery(string domain)
        {
            var query = new List<byte>();
            
            // 事务ID (随机)
            var random = new Random();
            query.Add((byte)random.Next(0, 256));
            query.Add((byte)random.Next(0, 256));
            
            // 标志：标准查询，递归查询
            query.Add(0x01); // QR=0, OPCODE=0, AA=0, TC=0, RD=1
            query.Add(0x00); // RA=0, Z=0, RCODE=0
            
            // 问题数量 = 1
            query.Add(0x00);
            query.Add(0x01);
            
            // 回答数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 权威记录数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 附加记录数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 域名部分
            var domainParts = domain.Split('.');
            foreach (var part in domainParts)
            {
                query.Add((byte)part.Length);
                query.AddRange(Encoding.UTF8.GetBytes(part));
            }
            query.Add(0x00); // 域名结束
            
            // 查询类型 A记录 = 1
            query.Add(0x00);
            query.Add(0x01);
            
            // 查询类 IN = 1
            query.Add(0x00);
            query.Add(0x01);
            
            return [.. query];
        }

        /// <summary>
        /// 从DNS响应中提取IP地址
        /// </summary>
        /// <param name="responseData">响应数据</param>
        /// <returns>IP地址</returns>
        private string? ExtractIpFromDnsResponse(byte[] responseData)
        {
            try
            {
                if (responseData.Length < 12) return null;
                
                // 检查响应码
                var rcode = responseData[3] & 0x0F;
                if (rcode != 0) return null; // 非零表示错误
                
                // 获取回答数量
                var answerCount = (responseData[6] << 8) | responseData[7];
                if (answerCount == 0) return null;
                
                // 跳过问题部分
                int position = 12;
                while (position < responseData.Length && responseData[position] != 0)
                {
                    int length = responseData[position];
                    position += length + 1;
                }
                position += 5; // 跳过结束的0和QType、QClass
                
                // 查找A记录
                for (int i = 0; i < answerCount && position < responseData.Length - 10; i++)
                {
                    // 跳过域名指针（2字节）
                    if (responseData[position] == 0xC0)
                    {
                        position += 2;
                    }
                    else
                    {
                        // 跳过域名
                        while (position < responseData.Length && responseData[position] != 0)
                        {
                            int length = responseData[position];
                            position += length + 1;
                        }
                        position++; // 跳过结束的0
                    }
                    
                    // 检查记录类型
                    var type = (responseData[position] << 8) | responseData[position + 1];
                    position += 2;
                    
                    // 跳过类
                    position += 2;
                    
                    // 跳过TTL
                    position += 4;
                    
                    // 获取数据长度
                    var dataLength = (responseData[position] << 8) | responseData[position + 1];
                    position += 2;
                    
                    if (type == 1 && dataLength == 4) // A记录，IPv4地址
                    {
                        // 提取IP地址
                        var ipBytes = responseData[position..(position + 4)];
                        return new IPAddress(ipBytes).ToString();
                    }
                    
                    position += dataLength;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"从DNS响应提取IP地址失败: {ex.Message}");
            }
            
            return null;
        }

        /// <summary>
        /// 创建反向DNS响应（PTR记录）
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="hostname">主机名</param>
        /// <returns>响应数据</returns>
        /// <summary>
        /// 创建DNS响应
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="ipAddress">IP地址</param>
        /// <returns>响应数据</returns>
        private byte[] CreateDnsResponse(byte[] requestData, string ipAddress)
        {
            try
            {
                // 解析IP地址
                var ipBytes = IPAddress.Parse(ipAddress).GetAddressBytes();
                
                // 创建响应列表
                var response = new List<byte>();
                
                // 复制请求头部（事务ID）
                response.AddRange(requestData[0..2]);
                
                // 设置响应标志（设置AA=1表示权威应答）
                response.Add(0x85); // QR=1, OPCODE=0, AA=1, TC=0, RD=1
                response.Add(0x80); // RA=1, Z=0, RCODE=0
                
                // 问题数量（从请求中复制）
                response.AddRange(requestData[4..6]);
                
                // 回答数量 = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // 权威记录数量 = 1（添加SOA记录）
                response.Add(0x00);
                response.Add(0x01);
                
                // 附加记录数量 = 0
                response.Add(0x00);
                response.Add(0x00);
                
                // 复制问题部分（域名查询部分）
                int questionStart = 12;
                int questionEnd = questionStart;
                
                // 找到问题部分的结束位置
                while (questionEnd < requestData.Length && requestData[questionEnd] != 0)
                {
                    int length = requestData[questionEnd];
                    questionEnd += length + 1;
                }
                questionEnd += 5; // 包括结束的0和QType、QClass
                
                if (questionEnd <= requestData.Length)
                {
                    response.AddRange(requestData[questionStart..questionEnd]);
                }
                
                // 添加回答记录
                // 指针到问题部分的域名（0xC0 0x0C）
                response.Add(0xC0);
                response.Add(0x0C);
                
                // 类型 A记录 = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // 类 IN = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // TTL = 300秒
                response.Add(0x00);
                response.Add(0x00);
                response.Add(0x01);
                response.Add(0x2C);
                
                // 数据长度 = 4（IPv4地址）
                response.Add(0x00);
                response.Add(0x04);
                
                // IP地址
                response.AddRange(ipBytes);
                
                // 添加权威记录（SOA记录，显示服务器名dns.local）
                // 指针到问题部分的域名（0xC0 0x0C）
                response.Add(0xC0);
                response.Add(0x0C);
                
                // 类型 SOA记录 = 6
                response.Add(0x00);
                response.Add(0x06);
                
                // 类 IN = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // TTL = 300秒
                response.Add(0x00);
                response.Add(0x00);
                response.Add(0x01);
                response.Add(0x2C);
                
                // 数据长度（计算SOA记录数据长度）
                // SOA记录包含：主DNS服务器名、管理员邮箱、序列号、刷新间隔、重试间隔、过期时间、最小TTL
                var soaData = CreateSoaRecordData("dns.local", "admin.dns.local");
                response.Add((byte)(soaData.Length >> 8));
                response.Add((byte)soaData.Length);
                
                // SOA记录数据
                response.AddRange(soaData);
                
                return [.. response];
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"创建DNS响应失败: {ex.Message}");
                
                // 返回一个基本的错误响应
                var basicResponse = new List<byte>();
                basicResponse.AddRange(requestData[0..2]); // 事务ID
                basicResponse.Add(0x81); // QR=1
                basicResponse.Add(0x83); // RCODE=3（域名不存在）
                basicResponse.AddRange(new byte[10]); // 其他字段设为0
                return [.. basicResponse];
            }
        }

        /// <summary>
        /// 创建SOA记录数据
        /// </summary>
        /// <param name="primaryNameServer">主DNS服务器名</param>
        /// <param name="responsiblePerson">负责人邮箱</param>
        /// <returns>SOA记录数据</returns>
        private static byte[] CreateSoaRecordData(string primaryNameServer, string responsiblePerson)
        {
            var soaData = new List<byte>();
            
            // 主DNS服务器名（dns.local）
            var primaryParts = primaryNameServer.Split('.');
            foreach (var part in primaryParts)
            {
                soaData.Add((byte)part.Length);
                soaData.AddRange(Encoding.UTF8.GetBytes(part));
            }
            soaData.Add(0x00); // 结束
            
            // 负责人邮箱（admin.dns.local）
            var personParts = responsiblePerson.Split('.');
            foreach (var part in personParts)
            {
                soaData.Add((byte)part.Length);
                soaData.AddRange(Encoding.UTF8.GetBytes(part));
            }
            soaData.Add(0x00); // 结束
            
            // 序列号 = 1
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x01);
            
            // 刷新间隔 = 3600秒（1小时）
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x0E);
            soaData.Add(0x10);
            
            // 重试间隔 = 600秒（10分钟）
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x02);
            soaData.Add(0x58);
            
            // 过期时间 = 86400秒（1天）
            soaData.Add(0x00);
            soaData.Add(0x01);
            soaData.Add(0x51);
            soaData.Add(0x80);
            
            // 最小TTL = 300秒
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x01);
            soaData.Add(0x2C);
            
            return [.. soaData];
        }

        /// <summary>
        /// 触发DNS请求处理事件
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="resolvedIp">解析的IP地址</param>
        /// <param name="sourceIp">来源IP</param>
        /// <param name="isCached">是否来自缓存</param>
        /// <param name="remoteEndPoint">远程端点</param>
        private void OnDnsRequestProcessed(string domain, string resolvedIp, string sourceIp, bool isCached = false, System.Net.IPEndPoint? remoteEndPoint = null)
        {
            DnsRequestProcessed?.Invoke(this, new DnsRequestEventArgs(domain, resolvedIp, sourceIp, isCached, remoteEndPoint));
        }

        /// <summary>
        /// 触发状态变化事件
        /// </summary>
        /// <param name="message">状态消息</param>
        /// <param name="isSuccess">是否成功</param>
        private void OnStatusChanged(string message, bool isSuccess)
        {
            StatusChanged?.Invoke(this, new DnsServiceStatusEventArgs(message, isSuccess));
        }

        #endregion

        #region IDisposable 实现

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing">是否释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    Stop();
                }
                
                _disposed = true;
            }
        }

        #endregion
    }
}